package j.util.web;

import j.util.DateUtils;
import j.util.Guid;
import j.util.New;
import j.util.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: jason
 * Date: 14-9-12 上午9:18
 */
public class MultiFileUploadController extends HttpServlet {
    private static Pattern FILENAME_EXTRACTOR_PATTERN = Pattern.compile("filename=\".+\"");

    protected String saveBasePath;

    @Override
    public void init(ServletConfig config) throws ServletException {
        saveBasePath = config.getInitParameter("saveBasePath");
        if(StringUtils.isNullOrEmpty(saveBasePath)){
            //没有配置此参数，则获取当前网站根目录的upload目录
            saveBasePath = config.getServletContext().getRealPath("/upload");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String uploadedPath = String.format("/upload/%s/", DateUtils.format(new Date(), "yyyy/MM/dd"));
        File f = new File(saveBasePath+uploadedPath);
        if(!f.exists()){
            f.mkdirs();
        }
        List<Map<String,String>> list = New.list();
        try{

            Collection<Part> parts = request.getParts();
            String fileName;
            Part part;
            Map<String,String> map;
            //遍历所有的表单内容，将表单中的文件写入上传文件目录
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext();) {
                part = iterator.next();
                System.out.println(part.getContentType());
                InputStream is = part.getInputStream();
                int read;
                while((read = is.read(buffer))!=-1){
                    bOut.write(buffer,0,read);
                }
                String v = new String(bOut.toByteArray(),"utf8");
                bOut.reset();
                System.out.println(v);
                //从Part的content-disposition中提取上传文件的文件名
                fileName = getFileName(part);
                if(fileName!=null){
                    map = New.map();
                    map.put("fileName",fileName);
                    fileName = uploadedPath+ Guid.newGuid()+fileName.substring(fileName.lastIndexOf("."), fileName.length());
                    map.put("savedPath",fileName);

                    part.write(saveBasePath+fileName);
                    //todo 获取上传基路径
                    //map.put("url", FApplication.getUploadImagePath(fileName));
                    list.add(map);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        String outS = j.util.JsonUtils.toJson(list);
        response.getWriter().write(outS);
    }

    /**
     * 从Part的Header信息中提取上传文件的文件名
     * @param part
     * @return  上传文件的文件名，如果如果没有则返回null
     */
    private String getFileName(Part part){
        //获取header信息中的content-disposition，如果为文件，则可以从其中提取出文件名
        String cotentDesc = part.getHeader("content-disposition");
        String fileName = null;
        Matcher matcher = FILENAME_EXTRACTOR_PATTERN.matcher(cotentDesc);
        if(matcher.find()){
            fileName = matcher.group();
            fileName = fileName.substring(10, fileName.length()-1);
        }
        return fileName;
    }
}
